import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
    state: {
        message: "我是vuex中state的数据",
        cartList: []
    },
    getters: {
        cartList(state){
            return state.cartList;
        },
    },
    mutations: {
        addCart(state, payload) {
            let isOld = false;
            state.cartList.filter(function (n) {
                if (n.id === payload.id) {
                    n.count += 1;
                    isOld = true;
                }
            })
            if (isOld === false) {
                let newItem=payload;
                newItem.count=1;
                state.cartList.push(newItem);
            }
        },
        onChangeCount(state,payload){
            state.cartList.filter(function (n){
                if(payload.id===n.id) {
                    n.count = payload.value;
                }
            })
            // console.log(payload)
        },
        selectItem(state,paylod){
            for(let n of state.cartList){
                if(n.id===paylod.id) n.checked=paylod.checked
            }
        },
        allChecked(state,payload){
            for (let n of state.cartList){
                if(n.checked!==payload.checked) n.checked=payload.checked
            }
        },
        deleteById(state,id){
            let list=state.cartList
            for(let i in list){
                if(list[i].id===id) list.splice(i,1);
            }
        }
    },
    actions: {},
    modules: {},
});

export default store